package com.yc.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.bbs.entity.Result;
import com.yc.bbs.entity.TblUser;
import com.yc.bbs.entity.UserEx;
import com.yc.bbs.service.BizException;
import com.yc.bbs.service.ITblUserService;
import com.yc.bbs.service.MailBiz;
import com.yc.bbs.service.impl.TblUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 * BBS论坛-用户表-6 前端控制器
 * </p>
 *
 * @author k
 * @since 2024-11-25
 */
@RestController
@RequestMapping("/tblUser")
public class TblUserController {
    @Autowired
    ITblUserService userService;
    @PostMapping("login")
    public Result login(@Valid TblUser tblUser, Errors errors, HttpSession session, HttpServletResponse response) throws BizException {
        if(errors.hasFieldErrors("uname")||errors.hasFieldErrors("upass")){
            throw new BizException("",errors.getAllErrors());
        }
        try {
            TblUser dbUser = userService.login(tblUser);
            session.setAttribute("myinfo",dbUser);
            String requestURI = (String) session.getAttribute("RequestURI");
            session.removeAttribute("RequestURI");
            dbUser.setRequestURI(requestURI);
            this.getAutoTime(tblUser,response);
            return new Result(1,"登录成功",dbUser);
        } catch (BizException e) {
            //添加自定义的错误信息
            errors.rejectValue("uname","uname or upass error",e.getMessage());
            //给业务异常添加错误
            e.setData(errors.getAllErrors());
            throw e;
        }
    }
    @RequestMapping("myinfo")
    public Result myinfo(@SessionAttribute(required = false) TblUser myinfo,
                        @CookieValue(required=false) String uname,
                         @CookieValue(required = false) String upass,
                         HttpSession session) throws BizException {
        if(myinfo==null){
            if(uname==null||upass==null){
                throw new BizException("未登录",null);
            }else{
                LambdaQueryWrapper<TblUser> queryWrapper = new LambdaQueryWrapper<TblUser>();
                queryWrapper.eq(TblUser::getUname,uname);
                queryWrapper.eq(TblUser::getUpass,upass);
                myinfo=userService.getOne(queryWrapper);
                session.setAttribute("myinfo",myinfo);
            }
        }
        return new Result(1,"已登录",myinfo);
    }
    @RequestMapping("logout")
    public ModelAndView logout(HttpSession session, ModelAndView mav, HttpServletResponse response, HttpServletRequest request){
        session.invalidate();
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("upass")||cookie.getName().equals("uname")){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        mav.setViewName("redirect:/index.html");
        return mav;
    }
    @PostMapping("upload")
    @ResponseBody
    public Result uploadHead(@RequestParam("head") MultipartFile file) throws IOException {
        //获取上传的文件名
        String filename=file.getOriginalFilename();
        String prefix= UUID.randomUUID().toString();
        String suffix = filename.replaceAll(".+\\.(\\w+)","$1");
        filename=prefix+"."+suffix;
        file.transferTo(new File("/Users/xiaoktongxue/Desktop/images/"+filename));
        String webPath = "image/head/"+filename;
        System.out.println("webPath = " + webPath);
        return new Result(1,"文件上传成功",webPath);
    }
    @PostMapping("reg")
    public  Result reg(@Valid UserEx user,Errors errors) throws BizException {
        userService.reg(user,errors);
        return new Result(1,"注册成功",null);
    }
    @RequestMapping("updateHead")
    public Result updateHead(@SessionAttribute(required = false) TblUser myinfo,String head) throws BizException {
        if(myinfo==null){
            throw new BizException("未登录",null);
        }
        int result = userService.updateHead(myinfo, head);
        if(result<=0){
            return new Result(500,"修改头像错误",null);
        }
        return new Result(200,"修改头像成功",null);
    }
    @PostMapping("auto")
    public String getAutoTime(TblUser userDto,
                              HttpServletResponse response){
        // 自动登录的安全问题

        Cookie cookie1 = new Cookie("uname", userDto.getUname());
        Cookie cookie2 = new Cookie("upass",userDto.getUpass());
        cookie1.setPath("/");
        cookie2.setPath("/");
        switch (userDto.getAutoTime()) {
            case 1:
                cookie1.setMaxAge(24*60*60);
                cookie2.setMaxAge(24*60*60);
                break;
            case 2:
                cookie1.setMaxAge(7*24*60*60);
                cookie2.setMaxAge(7*24*60*60);
                break;
            case 3:
                cookie1.setMaxAge(30*24*60*60);
                cookie2.setMaxAge(30*24*60*60);
                break;
            default:
                return "";
        }
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        return "redirect:/index.html";
    }
    @Autowired
    MailBiz mailBiz;
    @RequestMapping("forgetPwd")
    public Result forgetPwd(String uname,HttpSession session){
        LambdaQueryWrapper<TblUser> lqw=new LambdaQueryWrapper<>();
        lqw.eq(TblUser::getUname,uname);
        TblUser user=userService.getOne(lqw);
        session.setAttribute("forgetUser",user);
        if(user==null){
            return new Result(-1,"没有该账户",null);
        }
        String msg="忘记密码的验证码: ";
        String vcode=System.currentTimeMillis()+"";
        vcode=vcode.substring(vcode.length()-4);
        session.setAttribute("forgetVcode",vcode);
        msg+=vcode;
        mailBiz.sendSimpleMail("忘记密码的验证码","2943635722@qq.com",user.getEmail(),msg);
        //TODO 隐藏邮箱中间几位
        //设置有效期
        return new Result(1,"验证码已发送到你的邮箱",null);
    }
    @RequestMapping("resetPwd")
    public Result resetPwd(String vcode,String pwd,String repwd,
                            @SessionAttribute String forgetVcode,
                           @SessionAttribute TblUser forgetUser,
                           HttpSession session){
        if(forgetVcode==null){
            return new Result(-1,"未发送验证码",null);
        }
        if(!forgetVcode.equals(vcode)){
            return new Result(-2,"验证码错误",null);
        }
        if(!pwd.equals(repwd)){
            return new Result(-3,"两次密码不一致",null);
        }
        forgetUser.setUpass(pwd);
//        userService.save(forgetUser);
//        userService.updateById(forgetUser);
        userService.saveOrUpdate(forgetUser);
        session.removeAttribute("forgetUser");
        session.removeAttribute("forgetVcode");
        return new Result(1,"重置密码成功",null);
    }
}
